"""
生成随机验证码图片功能模块
"""

from PIL import Image, ImageDraw, ImageFont, ImageFilter  # 导入图片生成模块
from io import BytesIO
import random


def get_random_color():
    """获取随机颜色"""
    return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)


def get_random_code_img(request):
    """
    获取随机验证码
    :param request:
    :return:
    """
    img = Image.new('RGB', (130, 34), color=(get_random_color()))  # 设置显示图片格式：宽度 背景色

    # 向图片写入文本(验证码)
    draw = ImageDraw.Draw(img)
    # 设置字体文件路径，字体大小
    my_font = ImageFont.truetype("./web/static/msyh.ttc", size=20)
    # 生成随机字符串
    # def str_random():

    valid_code = ''
    for i in range(5):
        num_random = str(random.randint(0, 9))  # 0-9
        upper_str = chr(random.randint(65, 90))  # A-Z
        small_str = chr(random.randint(97, 122))  # a-z
        str_random = random.choice([num_random, upper_str, small_str])
        valid_code += str_random
        # 写入图片
        draw.text((i * 20 + 20, 5), str_random, get_random_color(), font=my_font)
    # 所处图片的坐标、文本内容、背景颜色、字体

    # 保存验证码到session 供全局使用
    request.session['image_code'] = valid_code
    request.session.set_expiry(60) # 主动修改session的过期时间为 60秒

    # 写干扰点
    for i in range(40):
        draw.point([random.randint(0, 130), random.randint(0, 34)], fill=get_random_color())

        # 写干扰圆圈
    for i in range(40):
        draw.point([random.randint(0, 130), random.randint(0, 34)], fill=get_random_color())
        x = random.randint(0, 34)
        y = random.randint(0, 130)
        draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random_color())

        # 画干扰线
    for i in range(5):
        x1 = random.randint(0, 34)
        y1 = random.randint(0, 130)
        x2 = random.randint(0, 34)
        y2 = random.randint(0, 130)

        draw.line((x1, y1, x2, y2), fill=get_random_color())
    img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)

    # 写入内存
    f = BytesIO()
    img.save(f, 'png')
    data = f.getvalue()  # 获取内存中的颜色图片

    return data

